package com.yonyou.pmclouds.basecom.util;

import java.beans.IntrospectionException;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author zm
 */
public class ReflectUtils {
    private static ConcurrentHashMap<Class, PropertyDescriptor[]> getterCache = new ConcurrentHashMap<>();
    private static ConcurrentHashMap<Class, PropertyDescriptor[]> setterCache = new ConcurrentHashMap<>();

    public static PropertyDescriptor[] getBeanSetters(Class<?> type) {
        PropertyDescriptor[] propertyDescriptors = setterCache.get(type);
        if (propertyDescriptors != null) {
            return propertyDescriptors;
        }
        propertyDescriptors = org.springframework.cglib.core.ReflectUtils.getBeanSetters(type);
        setterCache.putIfAbsent(type, propertyDescriptors);
        return propertyDescriptors;
    }

    public static PropertyDescriptor[] getBeanGetters(Class<?> type) {
        PropertyDescriptor[] propertyDescriptors = getterCache.get(type);
        if (propertyDescriptors != null) {
            return propertyDescriptors;
        }
        propertyDescriptors = org.springframework.cglib.core.ReflectUtils.getBeanGetters(type);
        getterCache.putIfAbsent(type, propertyDescriptors);
        return propertyDescriptors;
    }

    public static Method getBeanGetter(Class<?> beanClass, String propertyName) throws IntrospectionException {
        return new PropertyDescriptor(propertyName, beanClass).getReadMethod();
    }

    public static Method getBeanSetter(Class<?> beanClass, String propertyName) throws IntrospectionException {
        return new PropertyDescriptor(propertyName, beanClass).getWriteMethod();
    }

    public static Field getFieldByGetter(Class<?> modelClass, String getterName) throws NoSuchFieldException {
        String propName = org.apache.commons.lang3.StringUtils.uncapitalize(getterName.substring(3));
        return modelClass.getDeclaredField(propName);
    }

    public static Field getFieldBySetter(Class<?> modelClass, String setterName) throws NoSuchFieldException {
        String propName = org.apache.commons.lang3.StringUtils.uncapitalize(setterName.substring(3));
        return modelClass.getDeclaredField(propName);
    }

}
